<script lang="ts" setup>
import{toast,
    relaunch,
    getImage
} from '@/util/bussinessTool'
import {
    smsCaptchaOauth,
    tokenOauth
} from '@/api/auth.js'
import { computed, onMounted, reactive, ref } from 'vue'
import form from '@/util/vaildation' 
import { deepClone, isNotEmpty } from '@/util/localTool';
import {userStore} from '@/stores/userStore/userStore'
import {commonStore} from '@/stores/commonStore/commonStore'
import { store } from'@/stores/allStores'
import {useRouter} from 'vue-router'
const router = useRouter()
//const store = userStore()
let agree = ref(true)
let loading = ref(false)
let loginLoading = ref(false)
let loginForm:{[x:string]:any} = reactive({ grantType: 'phone' })
const rules = [{
    name: "phone",
    rule: ["required", "isMobile"],
    msg: ["请输入手机号码", "请输入正确的手机号码"]
}]
const loginRules = [{
    name: "phone",
    rule: ["required", "isMobile"],
    msg: ["请输入手机号码", "请输入正确的手机号码"]
}, {
    name: "smsCode",
    rule: ["required"],
    msg: ["请输入验证码"]
}]
const url = [{
    url: 'https://daojia.jiediqi.cn/publicPolicy/index.html#/pages/book/weixin/serviceAgreement',
    title: '平台服务协议'
}, {
    url: 'https://daojia.jiediqi.cn/publicPolicy/newPolicy/privacyPolicy.html',
    title: '隐私政策'
}, {
    url: 'https://daojia.jiediqi.cn/publicPolicy/index.html#/pages/book/weixin/responsibility',
    title: '责任声明'
}]
function onBook(index: number) {
    if (url[index].url.startsWith('https')) {
        /*
        uni.navigateTo({
            url: '/pages/publicPolicy/publicPolicy?payload=' + this.$encodePageParams(this.url[
                index])
        })
        */
    } else {
        /*
        uni.navigateTo({
            url: this.url[index].url
        })
        */
    }
}
onMounted(()=>{
    store.common.smsTimeRemainder = 0
    if(store.common.smsTimeRemainder > 0){
        loading.value = true
        timer()
    }  
})
function timer() {
    setTimeout(() => {
        store.common.smsTimeRemainder -= 1
        if (store.common.smsTimeRemainder !== 0) {
            timer()
        }
    }, 1000)
}
function onLogin() {
    let checkRes = form.validation(loginForm, loginRules)
    if (checkRes) {
        toast({
            message: checkRes,
        })
        return
    }
    if (!agree) {
        toast({
            message: '请阅读并同意相关协议条款',
        })
        return
    }
    if (loginLoading.value === true) {
        return
    }
    loginLoading.value = true
    if (isNotEmpty(store.user.wxUser)) {
        loginForm['wxUserId'] = store.user.wxUser.id
    }
    tokenOauth(loginForm).then((res:any) => {
        store.user.setData('tenantId',res.data.tenantId) 
        store.user.setData('accessToken',res.data.accessToken)
        store.user.setData('token',res.data.accessToken)
        store.user.setData('wxUser',res.data.wxUser)
        store.user.setData('userInfo',res.data.userInfo)
        delete res.data.wxUser
        //store.userInfo = deepClone(res.data) 
        toast({message:'登录成功',icon: 'success'})
        let historyLength = window.history.length
        if(historyLength>1){
            router.back()
        }else{
            relaunch({url:'home',param:{}})
        } 
    }).finally(() => {
        loginLoading.value = false
    })
}
function onCode() {
    if (store.common.smsTimeRemainder !== 0) {
        toast({
            message:`请等待${store.common.smsTimeRemainder}秒后尝试`,
        })
    } else {
        let checkRes = form.validation(loginForm,rules)
        if (checkRes) {
            toast({
                message: checkRes,
            })
            return
        }
        if (loading.value === true) {
            return
        }
        loading.value = true
        smsCaptchaOauth({
            phone: loginForm.phone
        }).then((res:any) => {
            store.common.smsTimeRemainder = 60
            timer()
            toast({message: "获取验证码成功"})
        }).finally(() => {
            loading.value = false
        })
    }
}
const codeBtn = computed(() => {
    let content = store.common.smsTimeRemainder === 0 ? '获取验证码' : `剩余${store.common.smsTimeRemainder}秒`
    let btnColor = store.common.smsTimeRemainder === 0 ? store.common.themeColorValue : store.common.btnGreyColor
    return{
        content:content,
        btnColor:btnColor
    } 
})
const loginBtn = computed(() => {
    let btnColor = loginLoading.value ? store.common.btnGreyColor:store.common.themeColorValue
    return{
        btnColor:btnColor
    } 
})
const policyColor = computed(() => {
    return {color:store.common.themeColorValue}
})
</script>
<template>
    <div class="head">
        <img class="logo" :src="getImage(store.app.logoImage)" />
        <div class=" container i-mx-5 i-round-2  i-text-14" >
            <div class="flex justify-between items-center i-p-10 divide-gray-300 border-b">
                <div class="w-1/5">手机号</div>
                <div class="w-4/5 flex justify-between" >
                    <input class="i-pl-10 i-text-15 placeholder-gray-200 w-3/6" placeholder="请输入手机号"
                        v-model="loginForm.phone" type="number" />
                        <van-button class="flex flex-shrink-0" round :color="codeBtn.btnColor" size="small" @click="onCode">{{codeBtn.content}}</van-button>
                </div>
            </div>
            <div class="flex justify-between items-center i-p-10">
                <div class="w-1/5">验证码</div>
                <input class="i-pl-10 i-text-14 i-py-3 w-4/5 placeholder-gray-200" placeholder="请输入验证码"
                    v-model="loginForm.smsCode"  type="number" maxlength="4" />
            </div>
        </div>
        <!--  
        <tm-button icon="icon-weixin" :icon-size="28" font-color="white" style="width:650rpx;" :height="78" block>微信一键登录（注册）</tm-button>
        -->
        <div class="flex justify-center items-center i-text-12 i-mt-30" >
            <div class="text-gray-300">注册登录即同意</div>
            <div @click="onBook(0)" :style="policyColor">《平台服务协议》</div>
            <div @click="onBook(1)" :style="policyColor">《隐私政策》</div>
            <div @click="onBook(2)" :style="policyColor">《责任声明》</div>
        </div>
        <van-button class="button-login" :loading="loginLoading" round :color="loginBtn.btnColor" size="small" @click="onLogin" block>立即登录</van-button>
    </div>
</template>
<style scoped>
.button-login{
    width:325px;
    margin-top: 10px;
    height:39px;
    font-weight: bolder;
}
.head{
    @apply flex items-center justify-center flex-col;
    margin-top: -40px;
    min-height: 100vh;
}
.logo{
    width: 200px;
    height: 200px;
    margin-bottom: 40px;
}
.container{
    @apply bg-white ;
    width: 325px;
}
</style>
